package com.jml.netty.base;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.util.concurrent.TimeUnit;

/**
 * netty 服务器端
 */
public class NettyServer {

    public void bind(int port) throws Exception {
        /**
         * Netty 抽象出两组线程池BossGroup和WorkerGroup
         * BossGroup专门负责接收客户端的连接, WorkerGroup专门负责网络的读写。
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup, workerGroup)
                    // 设定NioServerSocketChannel 为服务器端
                    .channel(NioServerSocketChannel.class)
                    //BACKLOG用于构造服务端套接字ServerSocket对象，标识当服务器请求处理线程全满时，
                    //用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1，Java将使用默认值50。
                    .option(ChannelOption.SO_BACKLOG, 100)
                    // 服务器端监听数据回调Handler
                    .childHandler(new ChildChannelHandler());
            //绑定端口, 同步等待成功;
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("当前服务器端启动成功...");
            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅关闭 线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            // 设置异步回调监听
            ch.pipeline().addLast(new JmlServerHandler());
////            1. 演示LineBasedFrameDecoder编码器,以\n\r进行区分
            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
            ch.pipeline().addLast(new StringDecoder());
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8091;
        new NettyServer().bind(port);
        System.out.println("NettyServer启动成功..");
    }


    public class JmlServerHandler extends SimpleChannelInboundHandler<Object> {

        /**
         * 服务器接收客户端请求
         *
         * @param ctx
         * @param msg
         * @throws Exception
         */
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg)
                throws Exception {
            //缓存到TaskQueue中，跳过这段代码执行下面的代码，当下面的代码执行完毕后，方法结束后，当前线程再去执行缓存在TaskQueue中的代码。
            ctx.channel().eventLoop().schedule(() -> {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //异步发送应答消息给客户端: 这里并没有把消息直接写入SocketChannel,而是放入发送缓冲数组中
                ByteBuf resp = Unpooled.copiedBuffer("www.jml2.com".getBytes());
                System.out.println(Thread.currentThread().getName() + "服务器端响应数据给客户端001");
                ctx.writeAndFlush(resp);
                //表示5秒后再来执行这段逻辑
            }, 5, TimeUnit.SECONDS);

            ctx.channel().eventLoop().schedule(() -> {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //异步发送应答消息给客户端: 这里并没有把消息直接写入SocketChannel,而是放入发送缓冲数组中
                ByteBuf resp = Unpooled.copiedBuffer("www.jml3.com".getBytes());
                System.out.println(Thread.currentThread().getName() + "服务器端响应数据给客户端002");
                ctx.writeAndFlush(resp);
                //表示5秒后再来执行这段逻辑
            }, 5, TimeUnit.SECONDS);


            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = new String(req, "UTF-8");
            System.out.println("服务器端接收到请求，读取到数据 : " + body);
            //异步发送应答消息给客户端: 这里并没有把消息直接写入SocketChannel,而是放入发送缓冲数组中
            ByteBuf resp = Unpooled.copiedBuffer("www.jml1.com".getBytes());
            ctx.writeAndFlush(resp);
        }

        //客户端首次连接就会调用这个方法
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {

        }

        //客户端主动断开连接就会走这个方法
        @Override
        public void channelInactive(ChannelHandlerContext ctx) {

        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        //客户端异常断开连接
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                throws Exception {
            ctx.close();
        }
    }
}